public class num25 {
    public ListNode reverseKGroup(ListNode head, int k) {
        ListNode dummyhead = new ListNode();
        dummyhead.next = head;
        ListNode prev = dummyhead;
        ListNode end = dummyhead;
        while (end.next != null){
            for (int i = 0; i < k && end != null; i++) {
                end = end.next;
                if(end == null){
                    break;
                }
            }
            ListNode start = prev.next;
            ListNode next = end.next;
            end.next = null;
            prev.next = reverseList(start);
            start.next = next;
            prev = start;
            end = prev;
        }
        return dummyhead.next;
    }
    public ListNode reverseList(ListNode head) {
        ListNode dummyhead = new ListNode();
        ListNode prev = head;
        while (prev != null){
            ListNode next = prev.next;
            prev.next = dummyhead;
            dummyhead = prev;
            prev = next;
        }
        return dummyhead;
    }
}
